package com.zcf.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zcf.dto.ArticleDto;
import com.zcf.mapper.ArticleMapper;
import com.zcf.pojo.Article;
import com.zcf.pojo.PageBean;
import com.zcf.pojo.Result;
import com.zcf.service.ArticleService;
import com.zcf.service.UploadService;
import com.zcf.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author zcf
 */
@Service("articleServiceImpl")
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private UploadService uploadService;
    @Override
    public Result add(ArticleDto articleDto) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDto, article);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);

        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        articleMapper.add(article);
        return Result.success();
    }


    @Override
    public PageBean<Article> page(Integer pageNum, Integer pageSize, Integer categoryId, String state) {

        //2.开启分页
        PageHelper.startPage(pageNum,pageSize);
        //查询满足条件的所有文章列表（第三个参数表示只能查询当前用户对应的文章）
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> list = articleMapper.list(categoryId, state, userId);

        Page<Article> page1=(Page<Article>) list;
        //3.利用Page类里面方法，得到总记录条数和当前页数据集合
        long total = page1.getTotal();
        List<Article> items = page1.getResult();
        return new PageBean<>(total,items);

    }



    @Override
    public Article detail(Integer id) {
      Article article=  articleMapper.select(id);
        return article;
    }


    @Override
    public void update(ArticleDto articleDto) {
        Article article=new Article();
        BeanUtils.copyProperties(articleDto,article);

        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }



    @Override
    public void delete(String id) {
        articleMapper.delete(id);
    }
}
